package com.laxia.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.helpers.MessageFormatter;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Slf4j
public class StringUtil extends StringUtils {

    private static final String CHARSET_DEFAULT = "UTF-8";

    public static String decode(String url) {
        if (isBlank(url)) {
            return url;
        }
        try {
            return URLDecoder.decode(url, CHARSET_DEFAULT);
        } catch (Exception ex) {
            return url;
        }
    }

    public static String encode(String url) {
        if (isBlank(url)) {
            return url;
        }
        try {
            return URLEncoder.encode(url, CHARSET_DEFAULT);
        } catch (Exception ex) {
            return url;
        }
    }

    public static boolean isEmpty(String... strings) {
        if (strings == null) {
            return true;
        }
        for (String str : strings) {
            if (isEmpty(str)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isAllBlank(String... values) {
        if (values == null || values.length == 0) {
            return true;
        }
        for (String value : values) {
            if (isNotBlank(value)) {
                return false;
            }
        }
        return true;
    }

    public static boolean isNumber(String str) {
        if (isBlank(str)) {
            return false;
        }
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取当前系统换行符
     */
    public static String getSystemLineSeparator() {
        return System.getProperty("line.separator", "\n");
    }

    /**
     * 字符串格式转换 占位符：{}
     */
    public static String format(String str, Object... args) {
        return MessageFormatter.arrayFormat(str, args).getMessage();
    }

    public static Integer parseInteger(String s) {
        return parseInteger(s, null);
    }

    public static Integer parseInteger(String s, Integer defaultValue) {
        if (isEmpty(s) || !isNumber(s)) {
            return defaultValue;
        }
        try {
            return Integer.valueOf(s);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static List<Integer> splitToIntegerList(String value) {
        return OptionalUtil.ofBlank(value)
                .map(o -> o.split(","))
                .map(Arrays::stream)
                .map(stream -> stream
                        .filter(StringUtil::isNumber)
                        .map(Integer::parseInt)
                        .collect(Collectors.toList())
                ).orElse(Collections.emptyList());
    }

    private static final char[] LETTER_AND_NUMBER = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();


    /**
     * 生成固定位数字
     *
     * @param length
     * @return
     */
    public static String random(int length) {
        int count = LETTER_AND_NUMBER.length;
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(count);
            sb.append(LETTER_AND_NUMBER[index]);
        }
        return sb.toString();
    }


    /**
     * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址;
     *
     * @param request
     * @return
     */
    public final static String getIpAddress(HttpServletRequest request) {
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址
        String ip = request.getHeader("X-Forwarded-For");
        try {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                if (ip == null || ip.length() == 0
                        || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0
                        || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("WL-Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0
                        || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_CLIENT_IP");
                }
                if (ip == null || ip.length() == 0
                        || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_X_FORWARDED_FOR");
                }
                if (ip == null || ip.length() == 0
                        || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();
                }
            } else if (ip.length() > 15) {
                String[] ips = ip.split(",");
                for (int index = 0; index < ips.length; index++) {
                    String strIp = (String) ips[index];
                    if (!("unknown".equalsIgnoreCase(strIp))) {
                        ip = strIp;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取ip异常", e);
        }
        return ip;
    }


    public static String randomNumber(int length) {
        String content = "0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(10);
            sb.append(content.charAt(index));
        }
        return sb.toString();
    }


    public static   String randomCode(){
        String letter = "ABCDEFGJKMNPQRSTUVWXYZ";
        String content = "0123456789";
        Random random = new Random();

        char charAt  = letter.charAt((int)(Math.random() * 26));
        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append(charAt);

        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(10);
            stringBuffer.append(content.charAt(index));
        }
        return  stringBuffer.toString();
    }

    public static  int randomScope(int maxValue){
        Random random = new Random();
        return  random.nextInt(maxValue) + 1;
       //return  1 + (int)(Math.random()*maxValue);
    }


}
